﻿using AutoMapper;
using NPOI.OpenXmlFormats.Wordprocessing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace OnlineEducation.Extensions
{
    /// <summary>
    /// 
    /// </summary>
    /// <seealso cref="AutoMapper.Profile" />
    public class AutoMapperConfig : Profile
    {
        public AutoMapperConfig()
        {
            /*
             下面的规则的由来：
             当使用EF 更新数据时， 
             一般的处理时，我们从View获取数据放到viewModel，然后，在根据Key在数据库中获取最新的数据Model，然后用ViewModel 里的数据，回填Model数据。
             如果用Auto mapper 直接map 过去，可能会导致某些我们不想更新的值被更新。
             所以有了以下的规则，目的就是只更新改变了的数据,对于那里viewModel 是默认值，则不更新。
             
             */
            ForAllMaps((obj, cnfg) => cnfg.ForAllMembers(opts => opts.Condition((src, dest, srcMember) =>
            {
                //源对象到目标对象的复制 map 规则
                Type type = srcMember.GetType();
                
                //1) 值类型，src 是默认值，不复制。
                if (type.IsValueType)
                {
                    return !srcMember.Equals(Activator.CreateInstance(type));
                }
                //2）引用类型，src 为默认值(null)，不复制。
                return srcMember != null;


            })));
            CreateMap<OnlineEducation.Data.Entities.Lesson, OnlineEducation.Data.Entities.Lesson>();
            CreateMap<OnlineEducation.Data.Entities.Course, OnlineEducation.Data.Entities.Course>();
            CreateMap<OnlineEducation.Data.Entities.Code, OnlineEducation.Data.Entities.Code>();
            CreateMap<OnlineEducation.Data.Entities.Booking, OnlineEducation.Data.Entities.Booking>();
            CreateMap<OnlineEducation.Data.Entities.CourseExam, OnlineEducation.Data.Entities.CourseExam>();
            CreateMap<OnlineEducation.Data.Entities.Holiday, OnlineEducation.Data.Entities.Holiday>();
            CreateMap<OnlineEducation.Data.Entities.LessonRecord, OnlineEducation.Data.Entities.LessonRecord>();
            CreateMap<OnlineEducation.Data.Entities.StudentProfile, OnlineEducation.Data.Entities.StudentProfile>();
            CreateMap<OnlineEducation.Data.Entities.TeacherProfile, OnlineEducation.Data.Entities.TeacherProfile>();
            CreateMap<OnlineEducation.Data.Entities.TeachingEvaluation, OnlineEducation.Data.Entities.TeachingEvaluation>();
            CreateMap<OnlineEducation.Data.Entities.TeachingPlan, OnlineEducation.Data.Entities.TeachingPlan>();
            CreateMap<OnlineEducation.Data.Entities.TeachingPlanItem, OnlineEducation.Data.Entities.TeachingPlanItem>();
            CreateMap<OnlineEducation.Data.Entities.AttendanceLog, OnlineEducation.Data.Entities.AttendanceLog>();


        }
    }
}
